﻿using System;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using dal.cgm_production_dao;
using Newtonsoft.Json;
using utils;

namespace bluetooth_test_localfile
{
    public partial class SetCode : Form
    {
        public string Code { get; private set; }
        public string Batch { get; private set; }
        public string Firmware { get; private set; }
        public SetCode()
        {
            InitializeComponent();
            InitializeMainForm();
            InitializeEventHandlers();
        }

        private void InitializeMainForm()
        {
            // 设置窗体属性
            this.Text = "设置CODE";
        }

        private void InitializeEventHandlers()
        {
            // 设置文本框的 TextChanged 事件处理程序
            pwdtextBox.TextChanged += TextBox_TextChanged;
            codetextBox.TextChanged += TextBox_TextChanged;
            batchtextBox.TextChanged += TextBox_TextChanged;
            firmtextBox.TextChanged += TextBox_TextChanged;
        }


        private void TextBox_TextChanged(object sender, EventArgs e)
        {
            TextBox textBox = sender as TextBox;
            Label label = null;

            if (textBox == pwdtextBox)
            {
                label = pwdlabel;
            }
            else if (textBox == codetextBox)
            {
                label = codelabel;
            }
            else if (textBox == batchtextBox)
            {
                label = batchlabel;
            }
            else if (textBox == firmtextBox)
            {
                label = firmlabel;
            }

            if (label != null && !string.IsNullOrWhiteSpace(textBox.Text))
            {
                label.Visible = false;
            }
        }

        private async void confirmbutton_Click_1(object sender, EventArgs e)
        {
            bool isValid = true;

            if (string.IsNullOrWhiteSpace(pwdtextBox.Text))
            {
                pwdlabel.Visible = true;
                pwdlabel.Text = "请输入密码";
                isValid = false;
            }
            else if (pwdtextBox.Text == "password")
            {
                pwdlabel.Visible = true;
                pwdlabel.Text = "密码不正确";
                isValid = false;
            }

            if (string.IsNullOrWhiteSpace(codetextBox.Text))
            {
                codelabel.Visible = true;
                codelabel.Text = "请输入CODE";
                isValid = false;
            }

            if (string.IsNullOrWhiteSpace(batchtextBox.Text))
            {
                batchlabel.Visible = true;
                batchlabel.Text = "请输入批号";
                isValid = false;
            }

            if (string.IsNullOrWhiteSpace(firmtextBox.Text))
            {
                firmlabel.Visible = true;
                firmlabel.Text = "请输入固件版本";
                isValid = false;
            }

            if (isValid)
            {
                #region

                //User auser = UserDao.GetUser("admin", pwdtextBox.Text);

                //if (string.IsNullOrEmpty(auser.account))
                //{
                //    MessageBox.Show("密码错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //}
                //else
                //{
                //    BluetoothTestSensorCodes acode = BluetoothTestSensorCodesDao.GetCode(codetextBox.Text, batchtextBox.Text, firmtextBox.Text);

                //    if (!string.IsNullOrEmpty(acode.code))
                //    {
                //        Code = codetextBox.Text;
                //        Batch = batchtextBox.Text;
                //        Firmware = firmtextBox.Text;
                //        this.DialogResult = DialogResult.OK;
                //        MessageBox.Show("Code设置成功！", "正确", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //        this.Close();
                //    }
                //    else
                //    {
                //        BluetoothTestSensorCodes xxx = new BluetoothTestSensorCodes
                //        {
                //            code = codetextBox.Text,
                //            batch = batchtextBox.Text,
                //            firmware = firmtextBox.Text,
                //        };
                //        if (BluetoothTestSensorCodesDao.Insert(xxx))
                //        {
                //            Code = codetextBox.Text;
                //            Batch = batchtextBox.Text;
                //            Firmware = firmtextBox.Text;
                //            this.DialogResult = DialogResult.OK;
                //            MessageBox.Show("Code设置成功！", "正确", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //            this.Close();
                //        }
                //        else
                //        {
                //            MessageBox.Show("Code设置失败，请重试！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //        }
                //    }
                //}
                #endregion

                var client = new HttpClientHelper(ConfigurationManager.AppSettings["ServerUrl"]);

                // 示例：发送JSON请求
                var jsonRequest = new
                {
                    name = "admin",
                    pwd = pwdtextBox.Text,
                    code = codetextBox.Text,
                    batch = batchtextBox.Text,
                    firmware = firmtextBox.Text,
                    sc = "30b9c3ca5e9911ef9aa806433e9aa661",
                    sv = "20b9c3ca5e9911ef9a806433e9aa661e"
                };

                try
                {
                    string jsonResponse = await client.PostJsonAsync("/api/SetCode", jsonRequest);

                    var response = JsonConvert.DeserializeObject<ApiResponse>(jsonResponse);
                    if (response.Code == 200)
                    {
                        MessageBox.Show("Code设置成功！", "正确", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Code = codetextBox.Text;
                        Batch = batchtextBox.Text;
                        Firmware = firmtextBox.Text;
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show(response.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }


                    // 处理 jsonResponse 的逻辑
                }
                catch
                {
                    MessageBox.Show("服务器内部错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }

            }
        }

        private void btnLoadFile_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.InitialDirectory = "c:\\";
                openFileDialog.Filter = "文本文件 (*.code)|*.code|所有文件 (*.*)|*.*";
                openFileDialog.FilterIndex = 1;
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // Get the path of the selected file
                    string filePath = openFileDialog.FileName;

                    // Read the content of the file
                    string fileContent = File.ReadAllText(filePath);

                    // Display the file content in the textbox
                    try
                    {
                        // 反序列化
                        Root root = JsonConvert.DeserializeObject<Root>(fileContent);

                        // 验证并使用反序列化的数据
                        if (root != null)
                        {
                            if (root.LotNumber <= 0)
                            {
                                MessageBox.Show("无效批号！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else if (root.HexString == null || root.HexString.Length != 256)
                            {
                                MessageBox.Show("无效Code！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                batchtextBox.Text = (root.LotNumber).ToString();
                                codetextBox.Text = string.Join(" ", Enumerable.Range(0, root.HexString.Length / 2).Select(i => root.HexString.Substring(i * 2, 2)));
                            }
                        }
                        else
                        {
                            MessageBox.Show("Code文件错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                }
            }

        }

    }
}
